package com.fly.glide;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;

/**
 * Created with Android Studio.
 * Package_Name：com.fly.glide
 * Project_Name：GlideDemo
 * User：郭鹏飞
 * Date：2015/12/9
 * Email：love518420@foxmail.com
 * Description：
 */
public class BitmapUtil {

    /**
     * 实现图片的圆角
     *
     * @param source 图片源
     * @param radius 圆角弧度
     * @return 实现了圆角的图片
     */
    public static Bitmap roundCorners(final Bitmap source, final float radius) {

        if (source == null)
            throw new NullPointerException("source is null");

        int width = source.getWidth();
        int height = source.getHeight();
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        Bitmap clipped = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(clipped);
        canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        source.recycle();
        return clipped;
    }

    /**
     * 将位图转换成圆形
     * @param source 位图源文件
     * @return 经过转换后的圆形位图
     */
    public static Bitmap circleBitmap(Bitmap source) {
        if (source == null)
            throw new NullPointerException("source is null");

        // 获取位图尺寸
        int width = source.getWidth();
        int height = source.getHeight();

        // 计算画布边长 取宽和高较小的一个值 并把该值的一半作为圆的半径
        // 原因自己想吧
        int sLenght = Math.min(width, height);
        int radius = sLenght / 2;

        Bitmap target = Bitmap.createBitmap(sLenght, sLenght, Bitmap.Config.ARGB_8888);
        // 根据target创建一块画布
        Canvas canvas = new Canvas(target);

        Paint paint = new Paint();
        paint.setAntiAlias(true);

        // 绘制圆
        canvas.drawCircle(radius, radius, radius, paint);

        // 绘制模式 16 相关资料 Xfermode
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        // 绘制位图
        canvas.drawBitmap(source, 0, 0, paint);

        // 返回经过处理以后的位图
        return target;
    }

}
